package com.crm.api.service.impl;

import com.crm.api.entity.Employee;
import com.crm.api.entity.WorkOrder;
import com.crm.api.entity.WorkOrderHistory;
import com.crm.api.mapper.EmployeeMapper;
import com.crm.api.mapper.WorkOrderMapper;
import com.crm.api.mapper.WorkOrderHistoryMapper;
import com.crm.api.service.WorkOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工单服务实现类
 */
@Slf4j
@Service
public class WorkOrderServiceImpl implements WorkOrderService {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private WorkOrderHistoryMapper workOrderHistoryMapper;

    @Override
    public Map<String, Object> getWorkOrders(Integer page, Integer size, String title, 
                                           String orderType, String priority, String status,
                                           Integer customerId, Integer businessId, 
                                           Integer assignedTo, Integer createdBy) {
        
        // 计算偏移量
        Integer offset = (page - 1) * size;
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", size);
        params.put("limit", size);  // 为了兼容性保留
        params.put("title", title);
        params.put("orderType", orderType);
        params.put("priority", priority);
        params.put("status", status);
        params.put("customerId", customerId);
        params.put("businessId", businessId);
        params.put("assignedTo", assignedTo);
        params.put("createdBy", createdBy);
        
        // 查询数据
        List<Map<String, Object>> workOrders = workOrderMapper.findWorkOrdersWithDetails(params);
        Integer total = workOrderMapper.countWorkOrders(params);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", workOrders);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);
        
        return result;
    }

    @Override
    public Map<String, Object> getMyWorkOrders(String username, Integer page, Integer size, 
                                             String title, String orderType, String priority, String status) {
        
        // 获取当前用户ID
        Integer userId = employeeMapper.findByUsername(username).getId();
        
        // 计算偏移量
        Integer offset = (page - 1) * size;
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", size);
        params.put("limit", size);  // 为了兼容性保留
        params.put("title", title);
        params.put("orderType", orderType);
        params.put("priority", priority);
        params.put("status", status);
        params.put("assignedTo", userId);
        
        // 查询数据
        List<Map<String, Object>> workOrders = workOrderMapper.findWorkOrdersWithDetails(params);
        Integer total = workOrderMapper.countWorkOrders(params);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", workOrders);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);
        
        return result;
    }

    @Override
    public WorkOrder getWorkOrderById(Integer id) {
        return workOrderMapper.findById(id);
    }

    @Override
    public Map<String, Object> getWorkOrderDetailById(Integer id) {
        return workOrderMapper.findByIdWithDetails(id);
    }

    @Override
    public WorkOrder createWorkOrder(WorkOrder workOrder, String creatorUsername) {
        // 获取创建人ID
        Integer createdBy = employeeMapper.findByUsername(creatorUsername).getId();
        workOrder.setCreatedBy(createdBy);
        
        // 生成工单编号
        String orderCode = generateOrderCode();
        workOrder.setOrderCode(orderCode);
        
        // 设置默认值
        if (workOrder.getStatus() == null || workOrder.getStatus().trim().isEmpty()) {
            workOrder.setStatus("待处理"); // 默认状态
        }
        if (workOrder.getPriority() == null || workOrder.getPriority().trim().isEmpty()) {
            workOrder.setPriority("中"); // 默认优先级
        }
        if (workOrder.getOrderType() == null || workOrder.getOrderType().trim().isEmpty()) {
            workOrder.setOrderType("技术支持"); // 默认类型
        }
        
        // 设置创建时间
        workOrder.setCreatedAt(new Date());
        workOrder.setUpdatedAt(new Date());
        
        // 插入数据
        workOrderMapper.insert(workOrder);
        
        // 记录创建历史
        String creatorName = employeeMapper.findByUsername(creatorUsername).getRealName();
        recordCreateHistory(workOrder.getId(), createdBy, creatorName);
        
        return workOrder;
    }

    @Override
    public WorkOrder updateWorkOrder(WorkOrder workOrder) {
        // 检查工单是否存在
        WorkOrder existingWorkOrder = workOrderMapper.findById(workOrder.getId());
        if (existingWorkOrder == null) {
            return null;
        }
        
        // 设置更新时间
        workOrder.setUpdatedAt(new Date());
        
        // 更新数据
        workOrderMapper.update(workOrder);
        
        return workOrderMapper.findById(workOrder.getId());
    }

    @Override
    public boolean deleteWorkOrder(Integer id) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        // 删除工单
        workOrderMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean assignWorkOrder(Integer id, Integer assignedTo) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        // 获取被分配人的姓名
        String assignedEmployeeName = null;
        if (assignedTo != null) {
            try {
                assignedEmployeeName = employeeMapper.findById(assignedTo).getRealName();
            } catch (Exception e) {
                log.warn("获取员工姓名失败: employeeId={}", assignedTo);
                assignedEmployeeName = "未知员工";
            }
        }
        
        // 分配工单
        Date now = new Date();
        workOrderMapper.assignWorkOrder(id, assignedTo, now, now);
        
        // 记录分配历史 (暂时使用系统操作，实际中应该传入当前用户信息)
        recordAssignHistory(id, workOrder.getAssignedTo(), assignedTo, 
                          workOrder.getCreatedBy(), "系统", assignedEmployeeName);
        
        // 如果状态是待处理，则改为处理中
        if ("待处理".equals(workOrder.getStatus())) {
            workOrderMapper.updateStatus(id, "处理中", now);
            // 记录状态变更历史
            recordStatusChangeHistory(id, workOrder.getStatus(), "处理中", 
                                    workOrder.getCreatedBy(), "系统");
        }
        
        return true;
    }

    @Override
    public boolean updateWorkOrderStatus(Integer id, String status) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        Date now = new Date();
        String oldStatus = workOrder.getStatus();
        
        // 更新状态
        workOrderMapper.updateStatus(id, status, now);
        
        // 记录状态变更历史
        recordStatusChangeHistory(id, oldStatus, status, workOrder.getCreatedBy(), "系统");
        
        // 根据状态更新相应的时间字段
        if ("已完成".equals(status)) {
            workOrderMapper.updateCompletedAt(id, now);
        } else if ("已关闭".equals(status)) {
            workOrderMapper.updateClosedAt(id, now);
        }
        
        return true;
    }

    @Override
    public boolean updateWorkOrderSolution(Integer id, String solution) {
        return updateWorkOrderSolution(id, solution, null);
    }

    @Override
    public boolean updateWorkOrderSolution(Integer id, String solution, String operatorUsername) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        // 更新解决方案
        workOrderMapper.updateSolution(id, solution, new Date());
        
        // 获取操作人信息
        Integer operatorId = workOrder.getCreatedBy();
        String operatorName = "系统";
        
        if (operatorUsername != null) {
            try {
                Employee operator = employeeMapper.findByUsername(operatorUsername);
                if (operator != null) {
                    operatorId = operator.getId();
                    operatorName = operator.getRealName();
                }
            } catch (Exception e) {
                log.warn("获取操作人信息失败: username={}", operatorUsername);
            }
        }
        
        // 记录解决方案历史
        recordSolutionHistory(id, solution, operatorId, operatorName);
        
        return true;
    }

    @Override
    public boolean updateCustomerFeedback(Integer id, String customerFeedback, Integer satisfactionRating) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        // 更新客户反馈
        workOrderMapper.updateCustomerFeedback(id, customerFeedback, satisfactionRating, new Date());
        return true;
    }

    @Override
    public boolean completeWorkOrder(Integer id) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        // 只有处理中或待回单的工单才能完成
        if (!"处理中".equals(workOrder.getStatus()) && !"待回单".equals(workOrder.getStatus())) {
            return false;
        }
        
        Date now = new Date();
        
        // 更新状态为已完成
        workOrderMapper.updateStatus(id, "已完成", now);
        workOrderMapper.updateCompletedAt(id, now);
        
        return true;
    }

    @Override
    public boolean closeWorkOrder(Integer id) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.findById(id);
        if (workOrder == null) {
            return false;
        }
        
        Date now = new Date();
        
        // 更新状态为已关闭
        workOrderMapper.updateStatus(id, "已关闭", now);
        workOrderMapper.updateClosedAt(id, now);
        
        return true;
    }

    @Override
    public Map<String, Object> getWorkOrderStats(String startDate, String endDate, String orderType, Integer assignedTo) {
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("orderType", orderType);
        params.put("assignedTo", assignedTo);
        
        // 获取各种统计数据
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", workOrderMapper.getTotalCount(params));
        stats.put("statusStats", workOrderMapper.getStatusStats(params));
        stats.put("typeStats", workOrderMapper.getTypeStats(params));
        stats.put("priorityStats", workOrderMapper.getPriorityStats(params));
        stats.put("satisfactionStats", workOrderMapper.getSatisfactionStats(params));
        stats.put("employeeStats", workOrderMapper.getEmployeeStats(params));
        stats.put("monthlyStats", workOrderMapper.getMonthlyStats(params));
        stats.put("averageProcessingTime", workOrderMapper.getAverageProcessingTime(params));
        
        return stats;
    }

    /**
     * 生成工单编号
     */
    private String generateOrderCode() {
        // 获取当前最大编号
        String maxCode = workOrderMapper.getMaxOrderCode();
        
        if (maxCode == null) {
            return "WO001";
        }
        
        // 提取数字部分
        String numberPart = maxCode.substring(2);
        int number = Integer.parseInt(numberPart) + 1;
        
        // 格式化为3位数字
        return String.format("WO%03d", number);
    }

    /**
     * 记录工单创建历史
     */
    private void recordCreateHistory(Integer workOrderId, Integer operatorId, String operatorName) {
        WorkOrderHistory history = new WorkOrderHistory();
        history.setWorkOrderId(workOrderId);
        history.setOperationType(WorkOrderHistory.OPERATION_CREATE);
        history.setContent("工单创建");
        history.setOperatorId(operatorId);
        history.setOperatorName(operatorName);
        history.setCreatedAt(new Date());
        
        workOrderHistoryMapper.insert(history);
    }

    /**
     * 记录工单分配历史
     */
    private void recordAssignHistory(Integer workOrderId, Integer oldAssignedTo, Integer newAssignedTo,
                                   Integer operatorId, String operatorName, String newAssignedName) {
        WorkOrderHistory history = new WorkOrderHistory();
        history.setWorkOrderId(workOrderId);
        history.setOperationType(WorkOrderHistory.OPERATION_ASSIGN);
        history.setOldValue(oldAssignedTo != null ? oldAssignedTo.toString() : "未分配");
        history.setNewValue(newAssignedTo != null ? newAssignedTo.toString() : "未分配");
        history.setContent("工单分配给: " + (newAssignedName != null ? newAssignedName : "未分配"));
        history.setOperatorId(operatorId);
        history.setOperatorName(operatorName);
        history.setCreatedAt(new Date());
        
        workOrderHistoryMapper.insert(history);
    }

    /**
     * 记录状态变更历史
     */
    private void recordStatusChangeHistory(Integer workOrderId, String oldStatus, String newStatus,
                                         Integer operatorId, String operatorName) {
        WorkOrderHistory history = new WorkOrderHistory();
        history.setWorkOrderId(workOrderId);
        history.setOperationType(WorkOrderHistory.OPERATION_STATUS_CHANGE);
        history.setOldValue(oldStatus);
        history.setNewValue(newStatus);
        history.setContent("状态从 '" + oldStatus + "' 更改为 '" + newStatus + "'");
        history.setOperatorId(operatorId);
        history.setOperatorName(operatorName);
        history.setCreatedAt(new Date());
        
        workOrderHistoryMapper.insert(history);
    }

    /**
     * 记录解决方案历史
     */
    private void recordSolutionHistory(Integer workOrderId, String solution, Integer operatorId, String operatorName) {
        WorkOrderHistory history = new WorkOrderHistory();
        history.setWorkOrderId(workOrderId);
        history.setOperationType(WorkOrderHistory.OPERATION_ADD_SOLUTION);
        history.setNewValue(solution);
        history.setContent("添加处理记录：" + solution);
        history.setOperatorId(operatorId);
        history.setOperatorName(operatorName);
        history.setCreatedAt(new Date());
        
        workOrderHistoryMapper.insert(history);
    }
}